package com.cunyu.action;

import java.io.IOException;
import java.net.URLEncoder;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cunyu.bean.Muser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cunyu.listener.RequestContext;
import com.cunyu.service.MuserService;

public class BaseController extends OpenController {

	private static Log logger = LogFactory.getLog(BaseController.class);

	@Resource
	MuserService  muserService;

	@Override
	public boolean before(HttpServletRequest req, HttpServletResponse res) {
		String uri = req.getRequestURI();
		if(uri != null && uri.startsWith("/channel")){
			return true ;
		}
		if (isvalid(req, res)) {
			return true;
		}
		try {
			String url = uri + (req.getQueryString() != null ? "?" + req.getQueryString() : "");
			url = URLEncoder.encode(url, req.getCharacterEncoding());
			res.getWriter()
					.write("<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /></head><body><script>location.href=\"/tologin?url="
							+ url + "\";</script></body></html>");
		} catch (IOException e) {
			logger.error("重定向发生错误。", e);
		}
		return false;
	}

	/**
	 * 检测cookie的有效性
	 * @param req
	 * @param res
	 * @return
	 */
	private boolean isvalid(HttpServletRequest req, HttpServletResponse res) {
		Cookie cookie = RequestContext.get().getCookie("token");
		if (cookie != null) {
			String value = cookie.getValue();
			Muser user = (Muser) timedCache.get(value);
			if (user == null) { // 判断
				user = muserService.getMuser(Long.parseLong(value));
				if (user == null)
					return false;
				user.setMenu(muserService.getMenuOne(user));
				timedCache.put(value, user);
			}
			return true;
		}
		return false;
	}

	public Muser getOnlineUser(){
		Cookie cookie = RequestContext.get().getCookie("token");
		return (Muser)timedCache.get(cookie.getValue());
	}

}
